package simpleTaskBoard.dao;

import java.util.List;

import simpleTaskBoard.entities.HistoryEntity;
import simpleTaskBoard.enums.ActionChangeEnum;
import ch.ivyteam.ivy.environment.Ivy;
import ch.ivyteam.ivy.process.data.persistence.IIvyEntityManager;

public class HistoryDAO {
	private IIvyEntityManager ivyEm;
	
	public HistoryDAO(){
		ivyEm = Ivy.persistence().get("PersistenceTask");
	}
	
	public List<HistoryEntity> findHistoryByTask(Long taskID){
		List<HistoryEntity> result = (List<HistoryEntity>) ivyEm.createQuery( "select h from HistoryEntity h where h.task.id = :taskID")
				.setParameter("taskID", taskID)
				.getResultList();
		return result;
	}
	
	public void addHistory(HistoryEntity history){
		ivyEm.merge(history);
	}
	
	public HistoryEntity findLastLogWorkByTask(Long taskID){
		HistoryEntity result = (HistoryEntity) ivyEm.createQuery( "select h from HistoryEntity h where h.task.id = :taskID and h.action =:logwork order by h.date desc")
				.setParameter("taskID", taskID)
				.setParameter("logwork", ActionChangeEnum.LOGWORK)
				.setMaxResults(1)
				.getSingleResult();
		return result;
	}
}
